<template>
  <div class="view-combox">
    <div class="subnav2">
      <div class="nav2">
        <ul v-if="cates && cates.length > 0">
          <li v-for="(item,index) in cates" :key="index">
            <a
              href="javascript:void(0)"
              :class="params.cate == item.key ? 'cur' : ''"
              @click.stop="selectCate(item.key, item.name)"
            >{{item.name}}</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="scrollbox">
      <!-- 头部 -->
      <v-header></v-header>
      <div class="dis10"></div>
      <div class="listbox aps8">
        <v-list
          api="system.get_sys_config"
          ref="list"
          cols="350,150,0,110"
          :params="params"
          cards="1"
          :hidSearch="false"
        >
          <template slot="search">
            <el-button
              class="operate"
              size="small"
              type="primary"
              icon="el-icon-plus"
              @click="edit(params)"
            >新增配置</el-button>&nbsp;&nbsp;&nbsp;
            <el-select v-model="params.union_id" size="small">
              <el-option
                :value="item.union_id"
                :label="item.name"
                v-for="(item, index) in menu"
                :key="index"
              ></el-option>
            </el-select>
            <span class="fr">
              <el-button class="operate" size="small" type="default" @click="clearcache">清除缓存</el-button>
              <el-button class="operate" size="small" type="default" @click="clearALlCache">清除全站缓存</el-button>
            </span>
          </template>
          <template slot="head" slot-scope="props">
            <thead>
              <tr class="tr">
                <th class="c1">名称</th>
                <th>标识</th>
                <th>值</th>
                <th>操作</th>
              </tr>
            </thead>
          </template>
          <template slot="item" slot-scope="props">
            <tr class="tr">
              <td @click="setBaseInfo(props)">
                <router-link to class="f14 font-blue">
                  <span class="tag tag-gray f12" v-if="props.item.inout == 1">私</span>
                  {{props.item.label}}
                  <span
                    class="font-gray2 f11"
                  >({{props.item.sort}})</span>
                </router-link>
              </td>
              <td class="font-gray">{{props.item.name}}</td>
              <td>
                <span class="font-gray">{{ props.item.value ? props.item.value : '-'}}</span>
              </td>
              <td>
                <el-button
                  size="mini"
                  title="编辑"
                  icon="el-icon-edit"
                  type="primary"
                  circle
                  @click="edit(props.item)"
                ></el-button>
                <el-button
                  v-if="!['cate','type','module'].some(el=> {return el===props.item.name})"
                  size="mini"
                  title="删除"
                  type="default"
                  icon="el-icon-delete"
                  circle
                  @click="del(props.item)"
                ></el-button>
              </td>
            </tr>
          </template>
        </v-list>
      </div>

      <!-- 编辑 -->
      <el-dialog :title="editData.title" :visible.sync="editData.status" width="800px" top="7vh">
        <div class="dialogform">
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            label-width="150px"
            label-position="right"
            class="demo-ruleForm"
          >
            <el-form-item label="名称" prop="label">
              <el-input v-model="form.label" class="w400"></el-input>
            </el-form-item>
            <el-form-item label="标识" prop="name">
              <el-input v-model="form.name" class="w400" :disabled="form.id > 0"></el-input>
            </el-form-item>

            <el-form-item label="分组" prop="cate">
              <el-select v-model="form.cate" placeholder="请选择上级模板">
                <el-option
                  v-for="(item,index) in $config('cate')"
                  :key="index"
                  :label="item.name"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择上级模板">
                <el-option
                  v-for="(item,index) in $config('type')"
                  :key="index"
                  :label="item.name"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" type="number" class="w200"></el-input>
            </el-form-item>
            <el-form-item label="是否私有" prop="inout">
              <el-radio-group v-model="form.inout">
                <el-radio :label="1">私有</el-radio>
                <el-radio :label="0">正常</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-show="form.type == 'input' || form.type == 'select'">
              <el-form-item label="默认值">
                <el-input v-model="form.value" class="w400"></el-input>
              </el-form-item>
            </div>
            <div v-show="form.type == 'upload'">
              <el-form-item label="上传图片">
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                      >
                        <i class="el-icon-download"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="imageUrl" alt />
                </el-dialog>
              </el-form-item>
            </div>
            <el-form-item prop="inlock">
              <el-button type="primary" @click="save">保 存</el-button>
              <el-button @click="editData.status = false">取 消</el-button>
            </el-form-item>
            <div class="edititembox" v-show="form.type == 'select' || form.type == 'item'">
              <v-editmore
                v-if="editData.status"
                ref="itemdata"
                name="配置项"
                :initdata="form.data"
                :newdata="{'key': '', value: '', name: ''}"
              >
                <template slot="head">
                  <colgroup>
                    <col width="200" />
                    <col />
                    <col width="150" />
                  </colgroup>
                  <thead>
                    <tr class="tr gray">
                      <th>标识</th>
                      <th>名称</th>
                      <th>值</th>
                      <th>-</th>
                    </tr>
                  </thead>
                </template>
                <template slot="item" slot-scope="props">
                  <tr>
                    <td>
                      <el-input size="mini" v-model="props.item.key"></el-input>
                    </td>
                    <td>
                      <el-input size="mini" v-model="props.item.name"></el-input>
                    </td>
                    <td>
                      <el-input size="mini" v-model="props.item.value"></el-input>
                    </td>

                    <td>
                      <el-button
                        size="mini"
                        icon="el-icon-top"
                        type="default"
                        circle
                        @click="$refs.itemdata.up(props.index)"
                      ></el-button>
                      <el-button
                        size="mini"
                        icon="el-icon-bottom"
                        type="default"
                        circle
                        @click="$refs.itemdata.down(props.index)"
                      ></el-button>
                      <el-button
                        size="mini"
                        icon="el-icon-close"
                        type="default"
                        circle
                        @click="$refs.itemdata.del(props.index)"
                      ></el-button>
                    </td>
                  </tr>
                </template>
              </v-editmore>
            </div>
          </el-form>
        </div>
        <!-- <div slot="footer" class="tc"></div> -->
      </el-dialog>
      <!-- 编辑结束 -->
      <!-- 详情开始 -->
      <v-baseinfo v-model="drawer.show" :name="drawer.name">
        <div class="wrapper-content" slot="sys/config">
          <div class="content-item">
            <span class="label">名称：</span>
            <span class="value">{{drawer.data.label || '-'}}</span>
          </div>
          <div class="content-item">
            <span class="label">标识：</span>
            <span class="value">{{drawer.data.name || '-'}}</span>
          </div>
          <div class="content-item">
            <span class="label">分组：</span>
            <span class="value">{{drawer.data.cates || '-'}}</span>
          </div>
          <div class="content-item">
            <span class="label">类型：</span>
            <span class="value">{{drawer.data.typeT || '-'}}</span>
          </div>
          <div class="content-item">
            <span class="label">排序：</span>
            <span class="value">{{drawer.data.sort || '-'}}</span>
          </div>
          <div class="content-item">
            <span class="label">是否私有：</span>
            <span class="value font-green" v-if="!drawer.data.inout">正常</span>
            <span class="value font-red" v-else>私有</span>
          </div>
          <div
            class="content-item"
            v-if="drawer.data.type == 'input' || drawer.data.type == 'select'"
          >
            <span class="label">默认值：</span>
            <span class="value">{{drawer.data.value || '-'}}</span>
          </div>
          <div
            class="content-item"
            style="display: flex;align-items: center;"
            v-if="drawer.data.type == 'select' || drawer.data.type == 'item'"
          >
            <span class="label">配置项：</span>
            <span class="table">
              <table>
                <thead>
                  <tr>
                    <td>标识</td>
                    <td>名称</td>
                    <td>默认值</td>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(val,inx) in drawer.data.data" :key="inx">
                    <td>{{ val.key || '-'}}</td>
                    <td>{{ val.name || '-'}}</td>
                    <td>{{ val.value || '-'}}</td>
                  </tr>
                </tbody>
              </table>
            </span>
          </div>
        </div>
      </v-baseinfo>
      <!-- 详情结束 -->
    </div>
  </div>
</template>
<script>
import { cacheConfig, cacheUnion } from "@cache";
export default {
  data() {
    return {
      form: {
        id: 0,
        label: "",
        name: "",
        type: "",
        cate: "",
        inout: 0,
        sort: 0,
        value: "",
        union_id: "",
        data: [],
        description: ""
      },
      editData: {
        status: false,
        title: "新增/修改配置",
        id: 0,
        cate: [],
        actionParam: { id: 0 }
      },
      rules: {
        label: [
          { required: true, message: "请输入配置名称", trigger: "blur" },
          { min: 1, message: "配置名称不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入标识", trigger: "blur" },
          { min: 1, message: "模板标识不能为空", trigger: "blur" }
        ]
      },
      params: {
        cate: "sys",
        union_id: "SYS"
      },
      config: {},
      cates: [],
      menu: [],
      imageUrl: "",
      dialogVisible: false,
      drawer: {
        show: false,
        data: {},
        name: "配置"
      }
    };
  },

  methods: {
    chooseMenu(val) {
      this.params.type = val.key;
    },
    selectCate(val) {
      this.params.cate = val;
    },
    edit(item) {
      this.editData.status = true;
      this.editData.id = item.id || 0;
      this.form.id = this.editData.id;
      this.form.cate = item.cate || this.params.cate || "sys";
      this.form.union_id = item.union_id || this.params.union_id || 0;
      this.form.name = item.name || "";
      this.form.label = item.label || "";
      this.form.inout = parseInt(item.inout) || 0;
      this.form.sort = item.sort || 0;
      this.form.type = item.type || "input";
      this.form.value = item.value || "";
      this.form.data = item.data || [];
      this.form.description = item.description || "";
    },
    save() {
      let that = this;
      this.form.sort = parseInt(this.form.sort);
      if (that.$refs.itemdata) {
        that.form.data = that.$refs.itemdata.getData();
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          let url =
            that.editData.id > 0
              ? "system.modify_sys_config"
              : "system.add_sys_config";
          that.$api.jpost(url, that.form).then(res => {
            if (res.status === 1) {
              that.$success(res.msg);
              that.$refs.list.fetchData();
              that.editData.status = false;
              // 清除浏览器本地数据
              cacheConfig.delete("YY:config");
              this.getCfg({ union_id: this.form.union_id });
            } else {
              that.$error(res.msg);
            }
          });
        }
      });
    },
    // 清除缓存
    clearcache() {
      this.$api
        .jget("system.del_sys_config_cache", { union_id: this.params.union_id })
        .then(res => {
          if (res.status === 1) {
            this.$success(res.msg);
          } else {
            this.$error(res.msg);
          }
        });
    },
    // 清除全站缓存
    clearALlCache() {
      this.$api.jget("admin.system_clear_cache").then(res => {
        if (res.status === 1) {
          this.$success(res.msg);
        } else {
          this.$error(res.msg);
        }
      });
    },
    getCfg(params) {
      this.$api
        .get("admin.get_cfg", params)
        .then(res => {
          if (res.status == 1) {
            cacheConfig.save(res.data);
            window.location.reload();
          }
        })
        .catch(() => {});
    },
    // 获取配置类型
    getCates() {
      this.cates = cacheConfig.load("YY:config").cate;
    },
    del(row) {
      let that = this;
      that
        .$confirm("此操作会将该彻底删除，不可恢复, 是否继续?", "删除提醒")
        .then(() => {
          that.$api
            .jpost("system.del_sys_config", {
              id: row.id,
              type: this.params.type
            })
            .then(res => {
              if (res.status === 1) {
                that.$success(res.msg);
                that.$refs.list.fetchData();
              } else {
                that.$error(res.msg);
              }
            });
        })
        .catch(() => {});
    },
    // 获取联盟信息
    getUnion() {
      this.menu = cacheUnion.load("YY:union");
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.dialogVisible = true;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    setBaseInfo(props) {
      this.drawer.show = true;
      this.drawer.data = props.item;
      // 设置类型
      let type = props.item.type;
      props.data.list.some(el => {
        if (el.id === 1) {
          el.data.forEach(ele => {
            if (ele.key === type) {
              this.drawer.data.typeT = ele.name;
            }
          });
        }
        return el.id === 1;
      });
      // 设置分组
      this.$config("cate").forEach(el => {
        if (props.item.cate === el.key) {
          this.drawer.data.cates = el.name;
        }
      });
    }
  },
  mounted() {
    this.getCates();
    this.getUnion();
  }
};
</script>

<style lang="scss" scoped>
.tabs {
  width: 290px;
}
/deep/.view-combox {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-form > .el-form-item:nth-last-child(2) {
    margin-bottom: 5px;
  }
}
</style>
